package com.david.core.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.request.FutureTarget
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

//使用场景：一次需要多张图片时（比如生成海报）。注：resultFunc执行在子线程，若要设置到view中需要外部回调中切换到主线程
fun downLoadImgs(imageUrls: List<String>, context: Context, errorFunc: ((String?) -> Unit)? = null, resultFunc: ((List<Bitmap?>) -> Unit)?) {
    CoroutineScope(Dispatchers.IO).launch {
        flow {
            val deferredImages: List<Deferred<Bitmap?>> = imageUrls.map { url ->
                async {
                    try {
                        BitmapFactory.decodeFile(Glide.with(context)
                            .asFile()
                            .load(url)
                            .submit(FutureTarget.SIZE_ORIGINAL, FutureTarget.SIZE_ORIGINAL)
                            .get().path)
                    } catch (e: Exception) {
                        Log.e("image", "download image $url error：${e.message}")
                        null
                    }
                }
            }
            val images = deferredImages.awaitAll()
            emit(images)
        }.catch {
            Log.e("image", "download images error：${it.message}")
            errorFunc?.invoke(it.message)
        }.collect {
            resultFunc?.invoke(it)
        }
    }
}